import { Col, Row, Spin, Icon } from "antd";
import { Card, ListView, Tabs, WhiteSpace } from "antd-mobile";
import moment from "moment";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { request, setMainFormTitle, setMainFormBack } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { getAge2, ROUTE_PATH } from "src/projects/app/util-tool";
import '../../buss-pub/news-list/index.less';
import { getGoodLookTimeShow } from "../activity-manage";
function MyBody(props: any) {
    return (
        <div className="am-list-body my-body" style={{ height: '100%' }}>
            {props.children}
        </div>
    );
}
/**
 * 组件：我的受理列表视图控件状态
 */
export interface MyAcceptanceViewState extends ReactViewState {
    /** 长列表数据 */
    dataSource?: any;
    /** 请求的数据 */
    list: any[];
    /** 下拉刷新 */
    pullLoading?: boolean;
    /** 长列表容器高度 */
    height?: any;
    /** 当前第几页 */
    page: any;
    /** 记录tab状态 */
    tab_status: string;
    tabs?: any;
    empty?: any;
    animating?: any;

    animating_all?: boolean;

    defaultImg?: string;
}
/**
 * 组件：我的受理列表视图控件
 */
export class MyAcceptanceView extends ReactView<MyAcceptanceViewControl, MyAcceptanceViewState> {
    constructor(props: any) {
        super(props);
        const ds = new ListView.DataSource({
            rowHasChanged: (r1: any, r2: any) => r1 !== r2
        });
        this.state = {
            dataSource: ds,
            list: [],
            pullLoading: false,
            height: document.documentElement!.clientHeight,
            page: [],
            tab_status: '',
            tabs: [],
            empty: [],
            animating: [],
            animating_all: true,
            defaultImg: 'https://www.e-health100.com/api/attachment/activityphoto/8336',
        };
    }
    componentDidMount() {
        request(this, AppServiceUtility.person_org_manage_service.check_permission!({ 'method': 'acceptance' }))
            .then((data: any) => {
                let tabs: any = [];
                let list: any = [];
                let page: any = [];
                let empty: any = [];
                let animating: any = [];
                if (data && data.length > 0) {
                    data.map((item: any) => {
                        tabs.push({ title: item.name });
                        list[item.name] = [];
                        page[item.name] = 1;
                        animating[item.name] = undefined;
                        empty[item.name] = undefined;
                    });
                }
                // 把第一个默认为请求助攻
                this.setState(
                    {
                        tabs,
                        list,
                        page,
                        empty,
                        animating,
                        animating_all: data && data.length === 0 ? false : true,
                        tab_status: data && data.length > 0 ? tabs[0].title : '',
                    },
                    () => {
                        this.getMyAcceptance(1, false);
                    }
                );
            }).catch(error => {
                console.info(error);
            });
    }
    /** 明细点击事件 */
    on_click_detail = (type: string, id: string) => {
        if (type === 'article') {
            this.props.history!.push(ROUTE_PATH.newsInfo + '/' + id);
        }
    }
    /** tab切换触发事件 */
    tab_click = (tab: any, index: number) => {
        let { page, empty } = this.state;
        this.setState(
            {
                tab_status: tab['title'],
                height: document.documentElement!.clientHeight,
            },
            () => {
                // 首次调用
                if (empty[tab['title']] === undefined) {
                    this.getMyAcceptance(page[tab['title']], true);
                }
            }
        );
    }
    /** 下拉事件 */
    onEndReached() {
        let { page, tab_status } = this.state;
        // console.log(`${tab_status}触发下拉`);
        this.getMyAcceptance(++page[tab_status], true, false);
    }
    getMyAcceptance(newPage: number, isConcact: boolean, needClear: boolean = true) {
        let { tabs, tab_status, list, empty, page, animating } = this.state;
        if (tabs.length === 0) {
            return;
        }
        // 防止重复发送
        if (animating[tab_status] === true) {
            return;
        }
        empty[tab_status] = undefined;
        animating[tab_status] = true;
        this.setState(
            {
                animating,
                // 完成使命
                animating_all: false,
                empty,
            },
            () => {
                request(this, AppServiceUtility.person_org_manage_service.get_current_user_acceptance!({ type: tab_status }, newPage, 10))
                    .then((data: any) => {
                        if (data && data.result.length > 0) {
                            // console.log(`现在设置${tab_status}有`);
                            list[tab_status] = list[tab_status].concat(data.result);
                            page[tab_status] = newPage;
                            empty[tab_status] = false;
                            animating[tab_status] = false;
                            this.setState({
                                list,
                                page,
                                empty,
                                animating,
                            });
                        } else {
                            // console.log(`现在设置${tab_status}空`);
                            empty[tab_status] = true;
                            animating[tab_status] = false;
                            this.setState({
                                animating,
                                empty,
                            });
                        }
                    });
            }
        );
    }
    setRow(name: string | undefined) {
        let defaultImg = this.state.defaultImg;
        switch (name) {
            case '床位预约':
                return (owData: any, sectionID: any, rowID: any) => {
                    if (owData['elder_info'].length === 0 || !owData['elder_info'][0]['personnel_info']) {
                        return (
                            <div />
                        );
                    }
                    let personnel_info = owData['elder_info'][0]['personnel_info'];
                    return (
                        <Card className='list-conten'>
                            <Row type='flex' justify='center' onClick={() => this.on_click_detail('bed', owData.id)}>
                                <Col className='list-col' span={10}><img className="activity-img" src={personnel_info['photo'] && personnel_info['photo'][0] ? owData['elder_info']['photo'][0] : defaultImg} /></Col>
                                <Col span={14} className='list-col'>
                                    <Row>姓名：{owData['elder_info'][0]['name'] || ''}</Row>
                                    <Row>性别：{personnel_info['sex'] || ''}</Row>
                                    <Row>年龄：{getAge2(owData['elder_info'][0]['id_card'] || '')}</Row>
                                    <Row>联系方式：{personnel_info['telephone'] || ''}</Row>
                                    <Row>受理方式：{owData['state']}</Row>
                                </Col>
                            </Row>
                        </Card>
                    );
                };
                break;
            case '高龄津贴':
                return (owData: any, sectionID: any, rowID: any) => {
                    if (owData['elder_info'].length === 0 || !owData['elder_info'][0]['personnel_info']) {
                        return (
                            <div />
                        );
                    }
                    let personnel_info = owData['elder_info'][0]['personnel_info'];
                    return (
                        <Card className='list-conten'>
                            <Row type='flex' justify='center' onClick={() => this.on_click_detail('old_age', owData.id)}>
                                <Col className='list-col' span={10}><img className="activity-img" src={personnel_info['photo'] && personnel_info['photo'][0] ? owData['elder_info']['photo'][0] : defaultImg} /></Col>
                                <Col span={14} className='list-col'>
                                    <Row>姓名：{owData['elder_info'][0]['name'] || ''}</Row>
                                    <Row>性别：{personnel_info['sex'] || ''}</Row>
                                    <Row>年龄：{getAge2(personnel_info['id_card'] || '')}</Row>
                                    <Row>联系方式：{owData['elder_info'][0]['telephone'] || ''}</Row>
                                    <Row>社区：{owData['village']}</Row>
                                    <Row>镇街：{owData['town_street']}</Row>
                                    <Row>金额：{owData['total_amount']}</Row>
                                    <Row>受理结果：{owData['apply_status']}</Row>
                                </Col>
                            </Row>
                        </Card>
                    );
                };
                break;
            case '养老资讯':
                return (owData: any, sectionID: any, rowID: any) => {
                    return (
                        <Card className='list-conten'>
                            <Row type='flex' justify='center' onClick={() => this.on_click_detail('article', owData.id)}>
                                <Col className='list-col' span={10}><img src={owData.hasOwnProperty('app_img_list') && owData.app_img_list.length > 0 ? owData.app_img_list[0] : defaultImg} style={{ height: '72pt', width: '110pt' }} /></Col>
                                <Col span={14} className='list-col'>
                                    <Row className="maxLine2" style={{ WebkitBoxOrient: 'vertical' }}><strong>{owData.title}</strong></Row>
                                    <Row>作者：{owData['author'] || ''}</Row>
                                    <Row className='list-t'>{moment(owData.create_date).format("YYYY-MM-DD hh:mm")}</Row>
                                </Col>
                            </Row>
                        </Card>
                    );
                };
                break;
            case '养老资讯':
                return (owData: any, sectionID: any, rowID: any) => {
                    return (
                        <Card className='list-conten'>
                            <Row type='flex' justify='center' onClick={() => this.on_click_detail('article', owData.id)}>
                                <Col className='list-col' span={10}><img src={owData.hasOwnProperty('app_img_list') && owData.app_img_list.length > 0 ? owData.app_img_list[0] : defaultImg} style={{ height: '72pt', width: '110pt' }} /></Col>
                                <Col span={14} className='list-col'>
                                    <Row className="maxLine2" style={{ WebkitBoxOrient: 'vertical' }}><strong>{owData.title}</strong></Row>
                                    <Row>作者：{owData['author'] || ''}</Row>
                                    <Row className='list-t'>{moment(owData.create_date).format("YYYY-MM-DD hh:mm")}</Row>
                                </Col>
                            </Row>
                        </Card>
                    );
                };
                break;
            case '活动信息':
                return (owData: any, sectionID: any, rowID: any) => {
                    return (
                        <Card className='list-conten' onClick={() => this.on_click_detail('activity', owData.id)}>
                            <Row type='flex' justify='center'>
                                <Col className='list-col' span={10}><img className="activity-img" src={owData.photo && owData.photo[0] ? owData.photo[0] : defaultImg} /></Col>
                                <Col span={14} className='list-col'>
                                    <Row>
                                        <Col span={24} className="happiness-info-row-title" style={{ WebkitBoxOrient: 'vertical' }}>{owData.activity_name}</Col>
                                    </Row>
                                    <Row className='list-row'>{owData.organization_name}</Row>
                                    <Row>{getGoodLookTimeShow(owData.begin_date, owData.end_date)}</Row>
                                    <Row>
                                        <Col span={4} className="font-orange">{!owData.hasOwnProperty('amount') || owData.amount === 0 || owData.amount === '0' || owData === '' || owData.amount === undefined ? '免费' : `￥${owData['amount'] || 0}`}</Col>
                                        <Col span={14}>已报名：{owData.participate_count || 0}/{owData.max_quantity}</Col>
                                        <Col span={6}><Icon className='item-icon-size' type="star" />{owData.collection_count || 0}</Col>
                                    </Row>
                                </Col>
                            </Row>
                        </Card>
                    );
                };
                break;
            case '服务产品':
                return (owData: any, sectionID: any, rowID: any) => {
                    return (
                        <Card className='list-conten'>
                            <Row type='flex' justify='center' onClick={() => this.on_click_detail('product', owData.id)}>
                                <Col className='list-col' span={10}><img className="activity-img" src={owData.picture_collection && owData.picture_collection[0] ? owData.picture_collection[0] : defaultImg} /></Col>
                                <Col span={14} className='list-col'>
                                    <Row>产品名称：{owData.name}</Row>
                                    <Row>产品描述：{owData.introduce}</Row>
                                    <Row>{owData.org_info && owData.org_info.length > 0 && owData.org_info[0]['name'] ? owData.org_info[0]['name'] : ''}</Row>
                                </Col>
                            </Row>
                        </Card>
                    );
                };
                break;
            default:
                return () => {
                    return (
                        <div />
                    );
                };
                break;
        }
    }
    render() {
        const { list, dataSource, animating, empty, tabs, tab_status, animating_all } = this.state;
        setMainFormTitle('受理');
        setMainFormBack('', () => {
            this.props.history!.push(ROUTE_PATH.mine);
        });
        // console.log(tab_status, list, animating, empty);
        return (
            <Row>
                {tabs && tabs.length > 0 ?
                    <Tabs
                        tabs={tabs}
                        initialPage={0}
                        onTabClick={(tab, index) => this.tab_click(tab, index)}
                    >
                        {tabs.map((item: any, index: number) => {
                            return (
                                <Row key={index}>
                                    {list[item.title].length > 0 ? <ListView
                                        ref={el => this['lv'] = el}
                                        dataSource={dataSource.cloneWithRows(list[item.title])}
                                        renderRow={this.setRow(item.title)}
                                        initialListSize={10}
                                        pageSize={10}
                                        renderBodyComponent={() => <MyBody />}
                                        style={{ height: this.state.height }}
                                        onEndReached={() => this.onEndReached()}
                                    /> : null}
                                    {tab_status !== '' && animating[tab_status] ? <Row>
                                        <WhiteSpace size="lg" />
                                        <Row style={{ textAlign: 'center' }}>
                                            <Spin size="large" />
                                        </Row>
                                        <WhiteSpace size="lg" />
                                    </Row> : null}
                                    {tab_status !== '' && empty[tab_status] !== undefined ? <Row>
                                        <WhiteSpace size="lg" />
                                        <Row className='tabs-content' type='flex' justify='center'>{list && list[tab_status] && list[tab_status].length ? '已经是最后一条了' : '无数据'}</Row>
                                        <WhiteSpace size="lg" />
                                    </Row> : null}
                                </Row>
                            );
                        })}
                    </Tabs> : null}
                {animating_all ? <Row>
                    <WhiteSpace size="lg" />
                    <Row style={{ textAlign: 'center' }}>
                        <Spin size="large" />
                    </Row>
                    <WhiteSpace size="lg" />
                </Row> : null}
                {tabs && tabs.length === 0 && animating_all === false ? <Row>
                    <WhiteSpace size="lg" />
                    <Row className='tabs-content' type='flex' justify='center'>无数据</Row>
                    <WhiteSpace size="lg" />
                </Row> : null}
            </Row>
        );
    }
}

/**
 * 组件：我的受理列表视图控件
 * 控制我的受理列表视图控件
 */
@addon('MyAcceptanceView', '我的受理列表视图控件', '控制我的受理列表视图控件')
@reactControl(MyAcceptanceView, true)
export class MyAcceptanceViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}